var jsMods = ['vue'];
var modelContrastMainVm;
CafeJS.models(jsMods, function(Vue) {
    modelContrastMainVm = new Vue({
        el: '#modelContrastMain',
        data: {
            isShow: true,
            bigModelContrastMapPopUp: null,
            bigMapResult: null,
            bigModelContrastMapPopUpView: "business/template/bigModelContrast-pop.html",
            queryDataClickCount: 0,
            selectedTime: {
                getDataUrl: "/drawmake/makedraw/getThumbImg",
                getDataUrlAwsnc: "/BuildProductTool/ModelCompareExportImage/getThumbImg",
            },
            //区域选择
            selectArea: 2,
            areas: [{
                key: '0',
                name: '天津'
            }, {
                key: '2',
                name: '海河'
            }],
            // 模式选择
            selectedModel : {
                id : "EC,NWGD,TJWRF",
                text : "EC+NWGD+TJWRF"
            },
            //区域选择是否禁用
            isDisable: false,
            models: [
                {
                    key: 'EC',
                    name: 'EC',
                    chinese: 'EC',
                },
                {
                    key: 'NWGD',
                    chinese: 'NWGD',
                    name: 'NWGD'
                },
                {
                    key: 'TJWRF',
                    chinese: 'TJWRF',
                    name: 'TJWRF'
                },
                {
                    key: 'GFS',
                    chinese: 'CMA-GFS',
                    name: 'GFS'
                },
                {
                    key: 'AWSNC',
                    chinese: '自动站实况',
                    name: 'AWSNC'
                },
                // {
                //     key: 'FUSH',
                //     chinese: 'FUSH',
                //     name: 'FUSH'
                // }
            ],
            // 要素
            selectedEle: 'TP12H',
            eles: [
                {
                    key: 'TP3H',
                    name: '3h降水',
                    unit: 'mm',
                    aging: 3
                },
                {
                    key: 'TP6H',
                    name: '6h降水',
                    unit: 'mm',
                    aging: 6
                },
                {
                    key: 'TP12H',
                    name: '12h降水',
                    unit: 'mm',
                    aging: 12
                },
                {
                    key: 'TP24H',
                    name: '24h降水',
                    unit: 'mm',
                    aging: 24
                },
                {
                    key: 'VIS',
                    name: '能见度',
                    unit: 'km',
                    aging: 3
                },
                {
                    key: 'TMP',
                    name: '2m气温',
                    unit: '℃',
                    aging: 3
                },
                {
                    key: 'RH',
                    name: '2m相对湿度',
                    unit: '%',
                    aging: 3
                },
                {
                    key: 'TCC',
                    name: '总云量',
                    unit: '%',
                    aging: 3
                },
                {
                    key: 'LCC',
                    name: '低云量',
                    unit: '%',
                    aging: 3
                },
                {
                    key: 'EDA10M',
                    name: '10M风',
                    unit: 'm/s',
                    aging: 3
                },
            ],
            eleSx: {
                'EC': { 'startSx': '000', 'endSx': '240' },
                'NWGD': { 'startSx': '000', 'endSx': '240' },
                'TJWRF': { 'startSx': '000', 'endSx': '096' },
                'GFS': { 'startSx': '000', 'endSx': '240' },
                'GRAPES-MESO': { 'startSx': '000', 'endSx': '240' },
                'JAPAN': { 'startSx': '000', 'endSx': '240' },
            },
            agings: {
                start: '0',
                end: '240',
                selStart: '0',
                selEnd: '72',
                interval: {
                    'TP3H': 3,
                    'TP6H': 6,
                    'TP12H': 12,
                    'TP24H': 24,
                    'VIS': 3,
                    'TMP': 3,
                    'RH': 3,
                    'TCC': 3,
                    'LCC': 3,
                    'EDA10M': 3,
                },
                colorLegend: {
                    'TP3H': '/business/szyb/css/images/legend/color_prep_3h.png',
                    'TP6H': '/business/szyb/css/images/legend/color_prep_6h.png',
                    'TP12H': '/business/szyb/css/images/legend/color_prep_12h.png',
                    'TP24H': '/business/szyb/css/images/legend/color_prep_24h.png',
                    'VIS': '/business/szyb/css/images/legend/visi.png',
                    'TMP': '/business/szyb/css/images/legend/eto2m.png',
                    'RH': '/business/szyb/css/images/legend/color_ecmf_rh_2m_humidity.png',
                    'TCC': '/business/szyb/css/images/legend/cloud.png',
                    'LCC': '/business/szyb/css/images/legend/cloud.png',
                    'EDA10M': '/business/szyb/css/images/legend/10m.png',
                },
            },
            // 时间间隔
            noData: '/business/szyb/css/images/legend/nothing.png',
            modelContrastMapLegend: '',
            datepicker: null,
            title: '12小时降水（mm）多模式对比邮票图（时效：0-60）',
            startTimeList: [],
            endTimeList: [],
            modelContrastAgings: [],
            modelContrastList: [],
        },
        mounted: function() {
            this.init();
        },
        methods: {
            init: function() {
                $('.modelContrastContentWrap').height($("#modal_modelContrast").height() - 120);
                $('.modelContrastContentWrap').width($("#modal_modelContrast").width() - 45);

                this.buildModelList();
                this.refreshTime();
                this.refreshTimeList();
                this.generateModelContrastList();
            },
            buildModelList() {
                //模式选择
                var _this = this;
                $("#jModel").off().on("mouseenter", function () {
                    if (!$(this).next().hasClass("jModel-select")) {
                        $(".jModel-y").find(".jModel-select").remove();
                        var curModels = $(this).attr("sid").split(",");
                        var models =_this.models;
                        _this.showOpt(this, "jModel-select");
                    }
                });
            },
            //初始化数值选择
            setDef: function(){
                $("#jModel").attr("sid",this.selectedModel.id).text(this.selectedModel.text);
            },
            //显示弹窗选项
            showOpt: function(that,cls){
                var _this = this;
                let curOpt = _this.selectedModel.id.split(",");
                let opts = _this.models;

                var $o = $('<div>');
                $o.addClass(cls);
                $.each(opts,function(){
                    var $ospan = $('<span>');
                    if($.inArray(this.key, curOpt) > -1){
                        $ospan.addClass("active");
                    }
                    $ospan.attr("sid",this.key).text(this.chinese);
                    $o.append($ospan);
                });

                $(that).after($o);

                $o.unbind().bind("mouseleave",function(){
                    $(this).remove();
                }).find("span").unbind().bind("click",function(){
                    if(!$(this).hasClass("active")){
                        $(this).addClass("active");
                    }else{
                        if($(this).siblings().hasClass("active")){
                            $(this).removeClass("active");
                        }
                    }
                    var oids = [];
                    var oTexts = [];
                    $o.find("span.active").each(function(){
                        oids.push($(this).attr("sid"));
                        oTexts.push($(this).text());
                    });

                    _this.selectedModel.id = oids.join(",");
                    _this.selectedModel.text = oTexts.join("+");

                    _this.generateModelContrastList();
                });
            },
            refreshTime: function() {
                var _this = this;
                _this.selectedTime.latesttime = $("#date").IDatePicker().getVal() + ":00";
                $("#modelContrast-datePicker").val(_this.selectedTime.latesttime);
                $.IDate(".modelContrast-datePanel", {
                    query: function query() {
                        modelContrastMainVm.queryData();
                    }
                });
                this.datepicker = $("#modelContrast-datePicker").IDatePicker()
            },

            refreshTimeList: function() {
                var _this = this;
                var _this = this;
                _this.startTimeList.splice(0);
                _this.endTimeList.splice(0);
                var interval = _this.agings.interval[_this.selectedEle];
                var aging = Number(interval);
                var start = Number(_this.agings.start);
                var end = Number(_this.agings.end);
                while (aging <= end) {
                    if (aging >= start) {
                        _this.startTimeList.push((Array(3).join('0') + aging).slice(-3));
                        _this.endTimeList.unshift((Array(3).join('0') + aging).slice(-3));
                    }
                    aging += interval;
                }
                this.agings.selStart = _this.startTimeList[0];
                this.agings.selEnd = _this.endTimeList[0];
            },

            getTitle: function() {
                var _this = this;
                var ele, mm, chinese = "";
                _this.eles.forEach(function(e) {
                    if (e.key == _this.selectedEle) {
                        ele = e.name;
                        mm = e.unit;
                        return false;
                    }
                })
                _this.models.forEach(function(m) {
                    if (m.key == _this.selectedModel) {
                        chinese = m.chinese;
                        return false;
                    }
                })
                var time = dateUtil.convertStringToDate8(_this.getStartTime());
                this.title = ele + '( ' + mm + ' )多模式对比邮票图（起报时间：' + time + '时   时效：' + Number(_this.agings.selStart) + '-' + Number(_this.agings.selEnd) + '）';
            },
            getStartTime: function() {
                var startTimeDate = new Date(this.datepicker.getVal() + ":00:00").format("yyyyMMddhhmmss");
                return startTimeDate;
            },
            //选择的要素
            getSelectedKeys: function(agingList) {
                var _this = this;
                var agingAttr = [];
                var startTime = this.getStartTime();

                var interval = this.agings.interval[this.selectedEle];

                var aging = Number(interval);
                var start = Number(this.agings.start) || 0;
                var end = Number(this.agings.end) || 0;
                while (aging <= end) {
                    if (aging >= start) {
                        agingAttr.push((Array(3).join('0') + aging).slice(-3));
                    }
                    aging += interval;
                }

                var orginAgings = agingAttr.join(',');
                agingAttr = agingList || agingAttr;

                var agings = agingAttr.join(',');

                return {
                    agingAttr: agingAttr,
                    startTime: startTime,
                    interval: interval,
                };
            },

            generateModelContrastList() {
                var startTimeDate = new Date(this.datepicker.getVal() + ":00:00");
                var that = this
                function getDateStr(addDayCount){
                    var dd = new Date(that.datepicker.getVal() + ":00:00");
                    var hour = dd.getHours()
                    dd.setHours(hour - 12*addDayCount)
                    var y = dd.getFullYear()
                    var m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1)
                    var d = dd.getDate()<10?"0"+dd.getDate():dd.getDate()
                    var h = dd.getHours()<10?"0"+dd.getHours():dd.getHours()
                    var f = dd.getMinutes()<10?"0"+dd.getMinutes():dd.getMinutes()
                    var s = dd.getSeconds()<10?"0"+dd.getSeconds():dd.getSeconds()
                    // return y+'-'+m+'-'+d+" "+h+":"+f
                    var obj = {
                        numDate:y+'-'+m+'-'+d+" "+h+":"+f,
                        textDate:d+'日'+h+'时'
                    }
                    return obj
                }
                var vm = this;
                var modelContrastList = [];
                var selModelList = vm.selectedModel.id.split(",");
                if(selModelList.length == 1 && selModelList[0] == 'AWSNC'){
                    alert('自动站实况不可单选')
                    return
                }
                var models = vm.models;
                var interval = vm.agings.interval[vm.selectedEle];
                var aging = Number(interval);
                var start = Number(vm.agings.selStart);
                // var end = selModelList.length == 1 ? Number(vm.agings.selEnd)+36 : Number(vm.agings.selEnd);
                var end = Number(vm.agings.selEnd)
                selModelList.forEach(selModel => {
                    models.forEach(modelItem => {
                       if(modelItem.key == selModel){
                           modelContrastList.push($.extend(true, {}, modelItem));
                       }
                    });
                });

                var agings = [];
                while (aging <= end) {
                    if (aging >= start) {
                        var timeTmp = new Date(startTimeDate.getTime() + (aging * 60 * 60 * 1000))
                        agings.push({
                            text: timeTmp.format("dd日hh时"),
                        });
                        modelContrastList.forEach(modelContrastItem => {
                            if(modelContrastItem.key == 'AWSNC'){

                            }
                            if(!modelContrastItem.agings){
                                modelContrastItem.agings = [];
                            }
                            var startP = aging - interval + "";
                            var endP = aging + "";
                            modelContrastItem.agings.push({
                                time: startTimeDate.format("yyyyMMddhhmss"),
                                element: vm.selectedEle.indexOf("TP") > -1 ? "TP1H" : vm.selectedEle,
                                mode: modelContrastItem.key,
                                startP: "00".substring(0, 2 - startP.length) + startP,
                                endP: "00".substring(0, 2 - endP.length) + endP,
                                title: timeTmp.format("dd日hh时"),
                                range: vm.selectArea,
                                url: 'null'
                            })
                        });
                    }
                    aging += interval;
                }
                if(modelContrastList.length == 1){
                //     console.log(agings)
                    modelContrastList.forEach((item,index)=>{
                        let first = Object.assign({},item)
                        modelContrastList.push(first)
                        let second = Object.assign({},item)
                        modelContrastList.push(second)
                        let third = Object.assign({},item)
                        modelContrastList.push(third)
                    })
                //     // modelContrastList[1].chinese = getDateStr(1).textDate
                    modelContrastList.forEach((item,index)=>{
                        if(index !== 0){
                            item.chinese = item.chinese + getDateStr(index).textDate
                            // agings.unshift({text:new Date(startTimeDate.getTime() - ((index-1) * 60 * 60 * 1000 * 12)).format("dd日hh时")})
                        }else{
                            item.chinese = item.chinese + getDateStr(0).textDate
                        }
                        item.agings.unshift()
                    })
                    function extend(source){
                        var target
                        if(typeof source === 'object'){
                            target = Array.isArray(source) ? [] : {}
                            for(var key in source){
                                if(source.hasOwnProperty(key)){
                                    if(typeof source[key] !== 'object'){
                                        target[key] = source[key]
                                    }else{
                                        target[key] = extend(source[key])
                                    }
                                }
                            }
                        }else{
                            target = source
                        }
                        return target
                    }
                    var demo = extend(modelContrastList)
                    demo[1].agings.forEach(item=>{
                        item.startP = (parseInt(item.startP) + 12).toString()
                        item.endP = (parseInt(item.endP) + 12).toString()
                        item.time = (new Date(startTimeDate.getTime() - (12 * 60 * 60 * 1000))).format("yyyyMMddhhmss")
                    })
                    demo[2].agings.forEach(item=>{
                        item.startP = (parseInt(item.startP) + 12*2).toString()
                        item.endP = (parseInt(item.endP) + 12*2).toString()
                        item.time = (new Date(startTimeDate.getTime() - (24 * 60 * 60 * 1000))).format("yyyyMMddhhmss")
                    })
                    demo[3].agings.forEach(item=>{
                        item.startP = (parseInt(item.startP) + 12*3).toString()
                        item.endP = (parseInt(item.endP) + 12*3).toString()
                        item.time = (new Date(startTimeDate.getTime() - (36 * 60 * 60 * 1000))).format("yyyyMMddhhmss")
                    })
                    modelContrastList = demo
                }
                modelContrastList.forEach((item,index)=>{
                    if(item.name == 'AWSNC'){
                        item.agings.forEach((item,index)=>{
                            item.startP = '00'
                            item.endP = 12
                            item.time = (new Date(startTimeDate.getTime() + (12 * 60 * 60 * 1000 * (index + 1)))).format("yyyyMMddhhmss")
                            console.log(item.time,index)
                        })
                    }
                })
                // console.log(JSON.stringify(modelContrastList))
                console.log(modelContrastList)
                vm.modelContrastAgings = agings;
                vm.modelContrastList = modelContrastList;
                vm.queryData();
            },

            //分批查询
            queryData: function() {
                var _this = this;
                if (Number(_this.agings.interval.selStart) > Number(_this.agings.interval.selEnd)) {
                    alert("预报时效开始时间不能大于结束时间");
                    return;
                }
                this.queryDataClickCount++;
                var clickCount = this.queryDataClickCount;

                _this.getTitle();
                _this.modelContrastMapLegend = this.agings.colorLegend[this.selectedEle];
                if(_this.modelContrastList){
                    _this.modelContrastList.forEach(modelContrast => {
                        modelContrast.agings.forEach(agingItem => {
                            _this.queryDataExe(agingItem, clickCount)
                        });
                    });
                }
            },
            /**
             * 查询方法
             * @param agingList 时效数组
             * @param last 是否是最后一次
             * @param clickCount 查询按钮点击次数
             */
            queryDataExe: function(agingItem, clickCount) {
                var _this = this;
                // console.log(agingItem)
                var url = agingItem.mode == 'AWSNC' ? 'http://10.226.120.112:9055/BuildProductTool/ModelCompareExportImage/getThumbImg' :_this.selectedTime.getDataUrlAwsnc
                // var url = _this.selectedTime.getDataUrl;
                $.get(
                    url,
                    {
                        fcstTime: agingItem.time,
                        element: agingItem.element,
                        mode: agingItem.mode,
                        startP: agingItem.startP,
                        endP: agingItem.endP,
                        range: agingItem.range
                    },
                    function(result) {
                        if (clickCount < _this.queryDataClickCount) {
                            return;
                        }
                        if (result) {
                            agingItem.url = "data:img/png;base64," + result;
                        }
                    }, "text");

            },
            getmodelContrastMapBox: function(url) {
                if (!url) {
                    return 'modelContrastMapBox  bgNothing';
                } else {
                    return 'modelContrastMapBox';
                }
            },
            /**
             * 打开大图
             */
            opengBigImg: function(modelContrastMapResult) {
                var width = $("#modal_modelContrast").width();
                var height = $("#modal_modelContrast").height();
                this.bigModelContrastMapPopUp = CafeJS.ModalBox({
                    id: "bigModelContrastMapPopUp",
                    container: 'cafe-busis-container',
                    title: '',
                    url: this.bigModelContrastMapPopUpView,
                    width: width,
                    height: height,
                    m_left: $("#modal_modelContrast").css("left"),
                    m_top: $("#modal_modelContrast").css("top"),
                    hide: true,
                    closed: function() {
                        CafeJS.ModalBoxClose("bigModelContrastMapPopUp");
                    }
                });
                this.bigMapResult = modelContrastMapResult;
            },

            insertArray: function(arr, item, index) {
                var a = arr.slice(0);
                a.splice(index, 0, item);
                return a;
            },
            changeStartTime: function(model) {
                this.agings.selStart = model.target.value;
                this.generateModelContrastList();
            },
            changeEndTime: function(model) {
                this.agings.selEnd = model.target.value;
                this.generateModelContrastList();
            },
            changeEle: function() {
                this.refreshTimeList();
                this.generateModelContrastList();
            },
            forward: function() {
                $("#modelContrast-datePicker").IDatePicker().toForward();
                this.generateModelContrastList();
            },
            backward: function() {
                $("#modelContrast-datePicker").IDatePicker().toBackward();
                this.generateModelContrastList();
            },
            newest: function() {
                $("#modelContrast-datePicker").IDatePicker().toNewest();
                this.generateModelContrastList();
            },
            changeArea: function() {
                this.generateModelContrastList();
            },
            changeMode: function() {
                this.refreshTimeList();
                this.generateModelContrastList();
            },
            srcoll(event) {
                var $scroller = $(event.target);
                $(".model_contrast_aging_empty_position").css("top", $scroller.scrollTop() + "px")
                $(".model_contrast_aging_empty_position").css("left", $scroller.scrollLeft() + "px")
                $(".model_contrast_model_header").css("top", $scroller.scrollTop() + "px")
                $(".model_contrast_model_body_position").css("left", $scroller.scrollLeft() + "px");
            }
        }
    });
});
